<template>
  <div class="flexContent">
    <div class="searchBox">
      <el-form ref="formRef" class="demo-form-inline" @submit.native.prevent label-position="left" label-width="auto">
        <div class="serFlexBox">
          <div class="inputBox">
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="暂无搜索">
                  <el-input style="width: 70%;" />
                </el-form-item>
              </el-col>

            </el-row>
          </div>
          <div class="btnBox">
            <el-button class="searchBtn" icon="el-icon-search">搜索</el-button>
            <el-button class="resetBtn" icon="el-icon-refresh-right">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <!-- <div class="add">
      <el-button class="addBtn" @click="addFn">新增</el-button>
    </div> -->
    <div class="table" id="tableBox" v-height>
      <div style="flex:1;">
        <vxe-table :column-config="{ resizable: true }" border class="tablebox" ref="xTable1"
          :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%" height="100%"
          size="medium" align="center">
          <vxe-column type="seq" width="80" title="序号" />
          <vxe-column align="center" title="分类名称">
            <template v-slot="{ row }">
              <span>{{ row.name }}</span>
            </template>
          </vxe-column>
          <vxe-column field="sort" align="center" title="排序" />
          <vxe-column field="imgUrl" align="center" title="图片">
            <template v-slot="{ row }">
              <el-image style="width: 50px; height: 50px;margin-top: 5px;" :src="row.imgUrl"
                :preview-src-list="[row.imgUrl]">
              </el-image>
            </template>
          </vxe-column>
          <vxe-column align="center" title="操作" v-if="$showFn(['genericGoodsCategory_edit'])">
            <template v-slot="{ row }">
              <el-button type="text" size="big" v-has="'genericGoodsCategory_edit'"
                style="margin-right: 10px; color: rgb(0, 132, 255)" @click.stop="edit(row)">编辑</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="paginationBox">
        <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
          layout="total,->, sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <AddDialog :close-on-click-modal="false" :show-dialog.sync="showDialog" :width="width" :title="title" @btnOk="btnOk"
      @close="close">
      <el-form ref="addFormRef" :disabled="title === '详情'" :model="addForm" :rules="addRules" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="22">
            <el-form-item label="分类名称" style="width: 100%">
              <span>{{ addForm.name }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="22">
            <el-form-item label="排序" style="width: 100%" prop="sort">
              <el-input v-model="addForm.sort" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="图片" prop="imgUrl">
              <el-upload v-if="!addForm.imgUrl" name="multipartFile" :limit="1" :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload" list-type="picture-card" :action="action" :data="upData"
                :headers="headers" :on-error="fileUploadError" class="imgUpload">
                <i size="12" class="el-icon-plus" />
                <br />
                <span class="txt">上传</span>
              </el-upload>
              <template v-if="addForm.imgUrl">
                <div style="display: flex; width: 100%">
                  <el-image v-if="addForm.imgUrl" style="height: 128px;object-fit: cover;border: 1px solid #ccc;"
                    :src="addForm.imgUrl" :preview-src-list="[addForm.imgUrl]" />
                  <div v-if="title !== '详情'" style="
												width: 50px;
                        height: 50px;
												border-radius: 5px;
												border: 1px dashed #ccc;
												text-align: center;
												color: #ccc;
												margin-left: 5px;
											">
                    <i style="cursor: pointer" class="el-icon-delete" @click="delImg" />
                  </div>
                </div>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </AddDialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth';
import AddDialog from "@/components/Goods/AddDialog";
import { getShopgenericCategoryList, updateShopgenericCategory } from '@/api/shopManagement'
export default {
  name: "MenuInfo",
  components: {
    AddDialog,
  },
  data() {
    return {
      headers: { token: getToken() },
      action: process.env.VUE_APP_UPLOAD_BASE_API + '/file/uploadFile',
      upData: {
        fileType: '0'
      },
      width: "50%",
      title: "编辑",
      showDialog: false,
      addForm: {
        name: "", // 菜单名称
        imgUrl: "", // 资源路径
        sort: "", //	排序
      },
      addRules: {
        sort: [
          {
            required: true,
            message: "请输入排序",
            trigger: "change",
          },
          {
            pattern: /^([0-9])+$/,
            message: "只能输入数字",
            trigger: "change",
          },
        ],
        imgUrl: [
          {
            required: true,
            message: "请上传图片",
            trigger: "change",
          },
        ],
      },
      categoryList: [],
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      categoryId: "",
    };
  },
  created() {
    this.getShopgenericCategoryList();
  },
  methods: {
    // 获取菜单列表
    async getShopgenericCategoryList() {
      const res = await getShopgenericCategoryList({ ...this.page });
      if (res.code === 200) {
        console.log(res);
        const result = res.data;
        this.categoryList = result.list;
        console.log(result, "data");
        // this.page.pageSize = result.pageSize
        this.page.pages = result.pages;
        this.page.pageNum = result.pageNum;
        this.page.total = result.total;
        const $table = this.$refs.xTable1
        $table.loadData(this.categoryList);
        console.log("categoryList", this.categoryList);
      } else {
        this.$message.error(res.message);
      }
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      console.log(`每页 ${val} 条`);
      this.getShopgenericCategoryList();
    },
    // 获取页数改变
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page.pageNum = val;
      this.getShopgenericCategoryList();
    },
    close() {
      this.showDialog = false;
      this.addForm = {
        name: "", // 名称
        imgUrl: "", // 资源路径
        sort: "", //	排序
      };
      this.$refs.addFormRef.resetFields();
    },
    btnOk() {
      if (this.title === "详情") {
        // 关闭
        this.close();
      } else if (this.title === "编辑") {
        // 修改
        this.$refs.addFormRef.validate(async (isOk) => {
          if (isOk) {
            const res = await updateShopgenericCategory({
              ...this.addForm,
              id: this.categoryId,
            });
            if (res.code === 200) {
              this.$message.success("修改成功");
              this.getShopgenericCategoryList();
              this.close();
            } else {
              this.$message.error(res.message);
            }
          } else {
            this.$message.warning("请检查输入信息");
          }
        });
      }
    },
    async edit(row) {
      this.showDialog = true;
      this.title = "编辑";
      console.log(row);
      this.addForm.name = row.name;
      this.addForm.sort = row.sort;
      this.addForm.imgUrl = row.imgUrl;
      this.categoryId = row.id;
    },
    handleAvatarSuccess(res, file) {
      this.addForm.imgUrl =
        this.$store.getters.imgBaseUrl +
        res.data.filePath +
        res.data.fileNewName;
      console.log(this.$store.getters.imgBaseUrl, '基地址');
      console.log(res);
      this.$message.success('上传成功');
      console.log(this.addForm.imgUrl);
    },
    beforeAvatarUpload(file) {
      // console.log('before', file)
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf('.'));
      const isOKType =
        fileType === '.jpg' ||
        fileType === '.png' ||
        fileType === '.jpeg';
      if (!isOKType) {
        this.$message.error('图片格式只能为jpeg/png/jpg');
      }

      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 5MB!');
      }
      return isLt2M && isOKType;
    },
    delImg() {
      this.addForm.imgUrl = '';
    },
    fileUploadError(res) {
      this.$message.error(res.message);
    },
  },
};
</script>

<style lang="scss" scoped>
.el-form-item {
  margin-bottom: 20px;
}

.imgUpload {
  ::v-deep .el-upload:hover {
    border-color: #409eff;
  }

  ::v-deep .el-upload {
    position: relative;
    margin-bottom: 10px;
    margin-left: 5px;
    width: 70px;
    height: 70px;
    line-height: 30px;
    padding-top: 5px;
  }

  .txt {
    color: #595858;
    font-size: 12px;
  }
}

.el-upload--picture-card i {
  font-size: 12px !important;
}

.el-button--small {
  padding: 9px 0;
}

::deep el-button {
  text-align: center;
}

.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-form-item--small.el-form-item {
  margin-bottom: 26px !important;
}

::v-deep .el-icon-circle-close:before {
  color: #fff;
}
</style>
